using System;
using System.IO;
using System.Windows.Forms;
using Widgetsphere.Core.Logging;

namespace Widgetsphere.Core.Util
{
	public partial class FileSystemHelper
	{
		#region Class's Log Switch
		private static readonly TraceSwitch _traceSwitch = LogClass.WSCommonUtil;
		#endregion

		public FileSystemHelper()
		{
		}

		public static bool ValidDirectoryString(string directoryPath)
		{
			try
			{
				var currentFolder = new DirectoryInfo(directoryPath);
				return true;
			}
			catch(Exception ex)
			{
				MessageLog.LogWarning(_traceSwitch, ex);
				return false;
			}
		}

		public static string DirectoryFromFileName(string fileName)
		{
			var fi =new FileInfo(fileName);
			return fi.DirectoryName;
		}

		#region SaveFile

		public static bool SaveFile(string path, string text)
		{
			try
			{
				//Remove the file if necessary
				if(System.IO.File.Exists(path))
					System.IO.File.Delete(path);

				var sw = System.IO.File.AppendText(path);
				sw.Write(text);
				sw.Close();
				return true;
			}
			catch(Exception ex)
			{
				throw;
			}
		}

		#endregion

		#region LoadFile

		public static string LoadFile(string path)
		{
			try
			{
				var sw = System.IO.File.OpenText(path);
				var retval = sw.ReadToEnd();
				sw.Close();
				return retval;
			}
			catch(Exception ex)
			{
				throw;
			}
		}

		#endregion

		#region ShowDialogOpenFile

		public static string ShowDialogOpenFile(string title, string filter)
		{
			var openFileDialog = new OpenFileDialog();
			openFileDialog.Title = title;
			openFileDialog.Filter = filter;
			if(openFileDialog.ShowDialog() == DialogResult.OK)
			{
				return openFileDialog.FileName;
			}
			return "";
		}

		#endregion

		#region ShowDialogSaveFile

		public static string ShowDialogSaveFile(string title, string filter)
		{
			var saveFileDialog = new SaveFileDialog();
			saveFileDialog.Title = title;
			saveFileDialog.Filter = filter;
			if(saveFileDialog.ShowDialog() == DialogResult.OK)
			{
				return saveFileDialog.FileName;
			}
			return "";
		}

		#endregion

	}
}
